package cpu.footprint.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import cpu.footprint.R;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.AppXUtilDao;
import cpu.footprint.api.MyApplication;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.GroupModel;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.FileUtil;

import static cpu.footprint.api.ApiUrl.URL_FILEPATH;

/**
 * Created by Administrator on 2017/4/8.
 */

@ContentView(R.layout.activity_groupmanage)
public class GroupManageActivity extends BaseActivity {
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    @ViewInject(R.id.image_group_head)
    private RoundedImageView image_head;//头像
    @ViewInject(R.id.edit_groupName)
    private EditText edit_groupName;
    @ViewInject(R.id.edit_groupRefreshSecond)
    private EditText edit_groupRefreshSecond;
    @ViewInject(R.id.edit_groupDescription)
    private EditText edit_groupDescription;
    private User user = new User();
    private GroupModel mGroupModel = new GroupModel();
    private MyApplication myApplication;
    private Context mContext;//上下文
    private Dialog mDialog;
    private AppXUtilDao mAppXUtilDao=new AppXUtilDao();//访问网络Dao层工具类
    private String HeadPicture;// 头像base64
    private String groupId="";
    private String mModilePhone;//电话号码
    private String mToken;//Token
    private Uri imageUri = Uri.parse(ApiUrl.URL_FILEPATH+"head.png");
    private static final int REQUEST_CODE_PICK_IMAGE=3;
    private static final int CROP_BIG_PICTURE=13;
    private static final int TAKE_BIG_PICTURE=14;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;
    private boolean IsEditing=false;//是否正在编辑
    private boolean IsUpdate=false;//是否更新了资料

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myApplication= (MyApplication) getApplication();
        mContext=GroupManageActivity.this;
        InitView();
        try {
            Bundle bundle = this.getIntent().getBundleExtra("bundle");
            mGroupModel= (GroupModel) bundle.getSerializable("group");
            if(mGroupModel!=null){
                InitData();
            }
        }catch (Exception e){
            e.printStackTrace();
            return;
        }
    }

    /**
     * 填充数据
     */
    private void InitData() {
        mToken=myApplication.getUser().getToken();
        mModilePhone=myApplication.getUser().getMobilePhone();
        groupId=mGroupModel.getId();
        edit_groupName.setText(mGroupModel.getName());
        edit_groupName.setSelection(edit_groupName.length());
        edit_groupRefreshSecond.setText(mGroupModel.getRefreshSecond()+" ");
        edit_groupRefreshSecond.setSelection(edit_groupRefreshSecond.length());
        edit_groupDescription.setText("\u3000\u3000"+mGroupModel.getDescription());
        edit_groupDescription.setSelection(edit_groupDescription.length());
        String imgUrl = ApiUrl.URL_HOST+mGroupModel.getHeadpicture();
        Picasso.with(this).load(imgUrl).placeholder(R.mipmap.head).into(image_head);
    }

    /**
     * 初始化View
     */
    private void InitView() {
        title_content.setText("群信息");
        title_menu_image.setVisibility(View.GONE);
        title_menu_text.setVisibility(View.VISIBLE);
        title_menu_text.setText("修改");
        InitEditUnEnable();
        mDialog=CreateDialogUtil.CreateDialog(this,"请稍后...",null);
    }
    @Event(value = {R.id.title_back,R.id.image_group_head,R.id.title_menu_text})
    private void OnClick(View v){
        switch (v.getId()){
            case R.id.title_back:{
                if(IsUpdate)
                    setResult(1);
                else{
                    setResult(2);
                }
                this.finish();
                overridePendingTransition(0,R.anim.fade);
            }break;
            case R.id.image_group_head:{
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                //    指定下拉列表的显示数据
                final String[] cities = {"拍照", "相册"};
                //    设置一个下拉的列表选择项
                builder.setItems(cities, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0: {
                                takePhone();
                            }
                            break;
                            case 1: {
                                choosePhone();
                            }break;
                        }
                    }
                });
                builder.show();
            }break;
            case R.id.title_menu_text:{
                if(IsEditing){
                    title_menu_text.setText("修改");
                    InitEditUnEnable();
                    UpdateGroupInfo();
                }else{
                    title_menu_text.setText("提交");
                    InitEditEnable();
                }
                IsEditing=!IsEditing;
            }break;
        }
    }

    /**
     * 修改群信息
     */
    private void UpdateGroupInfo() {
        String groupName=edit_groupName.getText().toString().trim();
        String groupRefreshSecond=edit_groupRefreshSecond.getText().toString().trim();
        String groupDescription=edit_groupDescription.getText().toString().trim();
        Map<String,String> map=new HashMap<>();
        map.put("mobilePhone", mModilePhone);
        map.put("id", groupId);
        map.put("Token", mToken);
        map.put("name", groupName);
        map.put("description", groupDescription);
        map.put("refreshSecond", groupRefreshSecond);
        mDialog.show();
        APIService.Post(ApiUrl.URL_GET_GROUP, map, new RespCallBack<BaseBean<GroupModel>>(this) {
            @Override
            public void onSuccess(BaseBean<GroupModel> result) {
                super.onSuccess(result);
                if (result.success) {
                    mGroupModel = result.data;
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });
    }

    /**
     * 控件不可用
     */
    private void InitEditUnEnable(){
        edit_groupName.setEnabled(false);
        edit_groupRefreshSecond.setEnabled(false);
        edit_groupDescription.setEnabled(false);
    }
    /**
     * 控件不可用
     */
    private void InitEditEnable(){
        edit_groupName.setEnabled(true);
        edit_groupRefreshSecond.setEnabled(true);
        edit_groupDescription.setEnabled(true);
    }
    /**
     * 重写后退函数
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if(IsUpdate)
                setResult(1);
            else{
                setResult(2);
            }
            GroupManageActivity.this.finish();
            overridePendingTransition(0,R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
    /**
     * Activity回调函数
     * @param req
     * @param res
     * @param data
     */
    public void onActivityResult(int req, int res, Intent data) {
        switch (req) {
            /**
             * 从相册中选取图片的请求标志
             */
            case REQUEST_CODE_PICK_IMAGE:
                if (res == Activity.RESULT_OK) {
                    try {
                        /**
                         * 该uri是上一个Activity返回的
                         */
                        imageUri= data.getData();
                        cropImageUri(imageUri, 400, 400, CROP_BIG_PICTURE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this,"程序崩溃",Toast.LENGTH_SHORT).show();
                    }
                }
                else{
                    Log.i("liang", "失败");
                }
                break;
            case CROP_BIG_PICTURE://截取图片
                if(imageUri != null){
                    Bitmap bitmap = decodeUriAsBitmap(imageUri);
                    image_head.setImageBitmap(bitmap);
                    bitmap = FileUtil.headimageZoom(bitmap);
                    FileUtil.saveMyBitmap(URL_FILEPATH+mGroupModel.getId()+"_ph.png",bitmap);
                    HeadPicture = FileUtil.bitmapToBase64(bitmap);
                    Map<String,Object> map=new HashMap<String,Object>();
                    map.put("mobilePhone", mModilePhone);
                    map.put("file",new File(URL_FILEPATH+mGroupModel.getId()+"_ph.png"));
                    map.put("groupId", mGroupModel.getId());
                    map.put("token", mToken);
                    updateGroupHead(map);

                }
                break;
            case TAKE_BIG_PICTURE://照相
                cropImageUri(imageUri, 400, 400, CROP_BIG_PICTURE);
                break;
            default:
                break;
        }
    }

    private void updateGroupHead(Map<String, Object> map) {
        mDialog.show();
        APIService.upLoadFile(ApiUrl.URL_GET_GROUP, map, new RespCallBack<BaseBean<GroupModel>>(this) {
            @Override
            public void onSuccess(BaseBean<GroupModel> result) {
                super.onSuccess(result);
                if (result.success) {
                    Toast("头像更新成功");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast("头像更新失败");
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });
    }

    /**
     * 选择图片
     * ********************************************************************
     */
    public void choosePhone(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE2);

        }else {
            choosePhoto();
        }
    }
    /**
     * 拍照
     */
    void takePhoto(){
//        /**
//         * 最后一个参数是文件夹的名称，可以随便起
//         */
        File file=new File(Environment.getExternalStorageDirectory(),"footprint");
        if(!file.exists()){
            file.mkdir();
        }
        /**
         * 这里将时间作为不同照片的名称
         */
        File output=new File(file,"head.png");
        try {
            if (output.exists()) {
                output.delete();
            }
            output.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 隐式打开拍照的Activity，并且传入CROP_PHOTO常量作为拍照结束后回调的标志
         */
        imageUri = Uri.fromFile(output);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_BIG_PICTURE);//or TAKE_SMALL_PICTURE
        overridePendingTransition(0,R.anim.fade);
    }
    /**
     * 从相册选取图片
     */
    void choosePhoto(){
        /**
         * 打开选择图片的界面
         */
        File chooseImage = new File(ApiUrl.URL_FILEPATH,"head.png");
        if (chooseImage.exists())
            chooseImage.delete();
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE); //
        overridePendingTransition(0,R.anim.fade);
    }
    /**
     * 剪切图片
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode){
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
        overridePendingTransition(0,R.anim.fade);
    }
    private Bitmap decodeUriAsBitmap(Uri uri){
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                takePhoto();
            } else{
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                choosePhoto();
            } else{
                // Permission Denied
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    /**
     * 检查权限
     */
    public void takePhone(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE2);
        }else {
            takePhoto();
        }
    }
}
